import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '../store'
import {getToken} from '@/utils/auth'
import constant from '@/utils/constant'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (!(config.url.lastIndexOf('/login') > -1)) {
      //把token添加到http协议请求的包头
      config.headers.token = sessionStorage.getItem('token')
    }

    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)


//在main.js设置全局的请求次数，请求的间隙
service.defaults.retry = 4;
service.defaults.retryDelay = 1000;

service.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {

  var config = err.config;
  // If config does not exist or the retry option is not set, reject
  if(!config || !config.retry) return Promise.reject(err);

  // Set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0;

  // Check if we've maxed out the total number of retries
  if(config.__retryCount >= config.retry) {
    // Reject with the error
    return Promise.reject(err);
  }

  // Increase the retry count
  config.__retryCount += 1;

  // Create new promise to handle exponential backoff
  var backoff = new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, config.retryDelay || 1);
  });

  // Return the promise in which recalls axios to retry the request
  return backoff.then(function() {
    return service(config);
  });
});

// response 拦截器
service.interceptors.response.use(
  response => {

    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data



    if (res.code !== constant.response.code.success) {
      //刷新token
      if (res.code === constant.response.code.tokenrefresh) {
          store.dispatch('SET_TOKEN',res.token)
          return  service(response.config);

      }

      if (res.code === constant.response.code.error || res.code === constant.response.code.exception || res.code === constant.response.code.noauth  ) {
          Message({
            message: res.message,
            type: 'error',
            duration: 5 * 1000
          })
      }
      if (res.code === constant.response.code.nologin  || res.code === constant.response.code.timeout  ) {
          MessageBox.confirm(
            '你已被登出，可以取消继续留在该页面，或者重新登录',
            '确定登出',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            store.dispatch('FedLogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
